package com.zl.freight.ui.activity;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.zl.freight.R;
import com.zl.freight.base.BaseActivity;
import com.zl.freight.mode.BaseUserEntity;
import com.zl.freight.utils.API;
import com.zl.freight.utils.ImageLoader;
import com.zl.freight.utils.SoapCallback;
import com.zl.freight.utils.SoapUtils;
import com.zl.zlibrary.adapter.UniversalAdapter;
import com.zl.zlibrary.adapter.UniversalViewHolder;
import com.zl.zlibrary.utils.GsonUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * @author zhanglei
 *         查询用户注册数据
 */
public class QueryUserActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_date_start)
    TextView tvDateStart;
    @BindView(R.id.tv_date_end)
    TextView tvDateEnd;
    @BindView(R.id.data_listView)
    ListView dataListView;
    @BindView(R.id.rg_choose_type)
    RadioGroup rgChooseType;
    @BindView(R.id.data_trl)
    TwinklingRefreshLayout dataTrl;
    @BindView(R.id.tv_query_data)
    TextView tvQueryData;

    private boolean isStart = true;
    private TimePickerView pvTime;
    private int page = 1;

    private List<BaseUserEntity> mList = new ArrayList<>();
    private UniversalAdapter<BaseUserEntity> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_user);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initData() {
        dataTrl.startRefresh();
    }

    private void initListener() {
        dataTrl.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                query();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                page++;
                query();
            }
        });

        rgChooseType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                page = 1;
                query();
            }
        });
    }

    private void initView() {
        tvTitle.setText("用户注册查询");
//        tvTitleRight.setText("查询");
        rgChooseType.check(R.id.rb_driver);
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
        tvDateEnd.setText(time);
        //时间选择器
        //选中事件回调
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
                if (isStart) {
                    tvDateStart.setText(time);
                } else {
                    tvDateEnd.setText(time);
                }
                query();
            }
        }).setType(new boolean[]{true, true, true, false, false, false}).build();

        mAdapter = new UniversalAdapter<BaseUserEntity>(mActivity, mList, R.layout.user_item_layout) {
            @Override
            public void convert(UniversalViewHolder holder, int position, BaseUserEntity userEntity) {
                String userData = "姓名：" + userEntity.getRealName() + "\n手机号：" + userEntity.getUserName() + "\n注册时间：" + userEntity.getCreateAt();
                holder.setText(R.id.tv_user_register_data, userData);
                CircleImageView imageView = holder.getView(R.id.iv_user_icon);
                ImageLoader.loadUserIcon(mActivity, userEntity.getUserIcon(), imageView);
            }
        };
        dataListView.setAdapter(mAdapter);
        dataTrl.setHeaderView(new ProgressLayout(mActivity));
    }

    @OnClick({R.id.iv_back, R.id.tv_title_right, R.id.tv_date_start, R.id.tv_date_end})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_title_right:
                query();
                break;
            case R.id.tv_date_start:
                isStart = true;
                pvTime.show();
                break;
            case R.id.tv_date_end:
                isStart = false;
                pvTime.show();
                break;
        }
    }

    /**
     * 查询
     */
    private void query() {
        Map<String, String> params = new HashMap<>();
        if (rgChooseType.getCheckedRadioButtonId() == R.id.rb_driver) {
            params.put("UserRole", "1");
        } else {
            params.put("UserRole", "2");
        }
        params.put("StartTime", tvDateStart.getText().toString());
        params.put("EndTime", tvDateEnd.getText().toString());
        params.put("PageIndex", page + "");
        params.put("PageSize", "10");

        SoapUtils.Post(mActivity, API.QueryUser, params, new SoapCallback() {
            @Override
            public void onError(String error) {
                Log.e("body", "");
            }

            @Override
            public void onSuccess(String data) {
                try {
                    JSONArray array = new JSONArray(data);
                    if (page == 1) {
                        mList.clear();
                        dataTrl.finishRefreshing();
                    } else {
                        dataTrl.finishLoadmore();
                    }
                    for (int i = 0; i < array.length(); i++) {
                        mList.add(GsonUtils.fromJson(array.optString(i), BaseUserEntity.class));
                    }
                    mAdapter.notifyDataSetChanged();
                } catch (Exception e) {

                }
            }
        });

        //查询注册人数
        SoapUtils.Post(mActivity, API.CountQueryUser, params, new SoapCallback() {
            @Override
            public void onError(String error) {
                Log.e("body", "");
            }

            @Override
            public void onSuccess(String data) {
                try {
                    JSONArray array = new JSONArray(data);
                    JSONObject object = array.optJSONObject(0);
                    String column1 = object.optString("Column1", "");
                    tvQueryData.setText("查询结果：该时间段内有" + column1 + "人注册");
                } catch (Exception e) {

                }
            }
        });

    }
}
